/**
 * Created by DukeCrushIt on 2015/8/5.
 */
//module game{
    class MoveMgr {
        public name:string;
        public frameItem:FrameItem;
        public constructor(){
            //super();
            this.items = [];
            this.name = "movemgr";
            this.frameItem = new FrameItem();
            this.frameItem.callObj = this;
            this.frameItem.callFun = this.update;
            FrameMgr.getInstance().addControll(this.frameItem);
        }
        private items:MoveItem[];
        private spareTime:number = 10;
        public update(deltaTime:number){
            if( this.items.length == 0) return;
            var itemLen:number = this.items.length - 1;
            var item:MoveItem;
            var startTime = egret.getTimer();
            var gap:number;
            for(var i = itemLen; i >= 0 ; i--){
                item = this.items[i];
                item.update(deltaTime);
                gap = egret.getTimer() - startTime;
                if( gap >= this.spareTime)
                    break;
            }
        }

        public addItem(item:MoveItem){
            if( this.items.indexOf(item) == -1){
                this.items.push(item);
            }
        }

        public delItem(item:MoveItem){
            var idx:number = this.items.indexOf(item);
            if( idx != -1){
                this.items.splice(idx, 1);
            }
            MoveMgr.reclaim(item);
        }

        public contains(item:MoveItem):boolean{
            return this.items.indexOf(item) != -1;
        }

        public removeAllHairItems(){
            var len:number = this.items.length;
            var item:MoveItem;
            var disObj:egret.DisplayObject;
            for( var idx = len - 1; idx >=0 ; idx--){
                item = this.items[idx];
                disObj = item.disObject;
                if( disObj instanceof Hair){
                    item.finish();
                }
            }
        }

        public finish(){
            var itemLen:number = this.items.length - 1;
            if( itemLen == -1 ) return;
            var item:MoveItem;
            for(var i = itemLen; i >= 0 ; i--){
                item = this.items[i];
                item.finish();
            }
        }

        private static _cache:MoveItem[]=[];
        public static reclaim(item:MoveItem){
            if( MoveMgr._cache.indexOf(item) == -1)
                MoveMgr._cache.push(item);
        }
        public static produce():MoveItem{
            if(MoveMgr._cache.length!=0)
                return MoveMgr._cache.pop();
            return new MoveItem();
        }

        private static _instance:MoveMgr;
        public static getInstance():MoveMgr{
            if( MoveMgr._instance == null)
                MoveMgr._instance = new MoveMgr();
            return MoveMgr._instance;
        }
    }
//}